import json
import os
import sys
from core.result_base import ResultBase
from common.logger import logger
from common.content_type import ContentType
from common.user_agent import useragent
from common.time_bdp import time_bdp
from api.general import general
import urllib3
urllib3.disable_warnings()

BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(BASE_PATH)


def general_info(access_token,tb_id,field_id,ftype,_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    常用编码解析
    :param tb_id:工作表id
    :param field_id:字段id
    :param ftype:常用编码解析类型，1为身份证号，手机号，邮政编码，车牌号
    :param _t:13位的时间戳
    :param _xsrf:
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    payload = {
        "tb_id":tb_id,
        "field_id":field_id,
        "ftype":ftype,
        "_t": _t,
        "_xsrf": _xsrf
    }

    headers = {
        "Content-Type": ContentType.MULTIPART_FORM_DATA.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }

    res = general.info(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("info ==>> 返回结果 ==>> {}".format(result.response.text))
    return result



def general_create(access_token,tb_id,field_id,ftype,flist,_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    身份证号解析
    :param tb_id:工作表id
    :param field_id:字段id
    :param ftype:常用编码解析类型，1为身份证号，手机号，邮政编码，车牌号
    :param _t:13位的时间戳
    :param _xsrf:
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    #flist = ["birthday","age","gender","province_id","province","city","district"]
    payload = {
        "tb_id":tb_id,
        "field_id":field_id,
        "ftype":ftype,
        "flist":json.dumps(flist),
        "_t": _t,
        "_xsrf": _xsrf
    }

    headers = {
        "Content-Type": ContentType.MULTIPART_FORM_DATA.value,
        "User-Agent": useragent.get_user_agent_one()
    }

    cookies = {
        "access_token": access_token
    }

    res = general.create(params=payload, headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("create ==>> 返回结果 ==>> {}".format(result.response.text))
    return result


# access_token = "273f26cc95427aa63207c106c3db46c4a2da9c73787cbfd6"
# tb_id = "tb_ca156f21b8684dcd8a0f23c47f843916"
# field_ids = ["fk54288ff9"]
#
# # tb_id = "tb_1e4d8399a32340769bc9e42f32e26f2c"
# # field_ids = ["fk4ef020c5"]
# field_url_preview(access_token,tb_id,field_ids)




